<!-- 习题练习页面 -->
<template>
	<view>
		<u-navbar :back-icon-color="'#fff'" :title-color="'#fff'" :border-bottom="false" :title="'在线考试'"
			:background="{ background: '#0B56B1' }"></u-navbar>
		<!-- 背景图 -->
		<view class="exerc-back" v-if="showPage">
			<image src="/static/exerc/back.png" mode="widthFix" />
		</view>
		<view class="exerc-content" :style="{ bottom: showExerc ? '116upx' : '0' }" v-if="showPage">
			<h2 style="text-align: center;color: #fff;">{{ this.exercConfig.exercTitle }}</h2>
			<!-- 顶部选项卡 -->
			<view class="exerc-tab module-back su-sticky">
				<!-- 答题时间 -->
				<text class="exerc-timer">
					<text class="wkfont ticon">&#xe65f;</text>
					<text class="text-time">
						<text v-if="minutes < 10">0{{ minutes }}:</text>
						<text v-else>{{ minutes }}:</text>
						<text v-if="seconds < 10">0{{ seconds }}</text>
						<text v-else>{{ seconds }}</text>
					</text>
				</text>
				<!-- 答题卡 -->
				<text class="exerc-sheet" @click="showExerc = !showExerc">
					<text class="wkfont dticon">&#xe617;</text>
					<text :class="[!showExerc ? 'select' : '']">答题卡</text>
				</text>
			</view>
			<!-- 题目信息 -->
			<swiper class="exerc-swiper" :circular="false" :indicator-dots="false" :current="swiperIndex"
				:autoplay="false" v-if="showExerc" @change="swiperChange">
				<swiper-item v-for="(item, index) in exercList" :key="item.name" :item-id="item.name">
					<exerc-item v-if="!isJiexi && !isTrue" :item-data="item" :item-index="index" :exerc-config="exercConfig"
						@select="itemSelect" />
					<answer-item v-else :itemData="item" :itemIndex="index" :exercConfig="exercConfig"></answer-item>
				</swiper-item>
			</swiper>
			<!-- 答题卡 -->
			<answer-sheet v-else :exerc-list="exercList" @select="sheetSelect" />
		</view>
		<!-- 底部提交按钮 -->
		<view class="exerc-bottom su-border2" v-if="showExerc && showPage && !isJiexi && !isTrue">
			<button class="su-button" @click="submitExerc">提交答案</button>
		</view>
		<u-modal v-model="show2" :content="'提交后不可修改，请您检查后确认是否提交'" @confirm="formSubmit"
			:show-cancel-button="true"></u-modal>
		<!-- <u-popup v-model="show2" @close="this.show2 = false" :closeable="true" mode="center"
			overlayOpacity='0.5'>
			<view class="textInPopup">
				<text>提交后不可修改，请您检查后确认是否提交！</text>
				<button class='buttonInPopup' @click='formSubmit'>确认提交</button>
			</view>
		</u-popup> -->
		<!-- 提交反馈 -->
		<result v-if="showResult" :sub-info="submitData" @result="resultFunc" />
		<view class="exerc-bottom su-border2" v-if="showResult">
			<button class="su-button" @click="goBack()">完成</button>
		</view>
	</view>
</template>
<script>
/**
 * 习题练习页面
 */
import exercItem from '../comp/exerc-card.vue'
import answerSheet from '../comp/answer-sheet.vue'
import answerItem from '../comp/answer-item.vue'
import result from './result.vue'
import mockJson from '../mock/exerc.json'
import { isEmpty } from "@/utils";
import { startCountdown, expTopic, handleSubmit } from '../js/exerc-utils.js'
export default {
	components: { exercItem, answerSheet, result, answerItem },
	data() {
		return {
			show2: false,
			showPage: false,
			showResult: false,
			showExerc: true,
			// 题目列表
			exercList: [],
			exercTimer: null,
			// 习题配置信息
			exercConfig: {},
			minutes: 0,
			seconds: 0,
			// 当前索引
			swiperIndex: 0,
			canback: false,
			submitData: {},
			labelId: '',
			surveyId: '',
			answer: [],
			isJiexi: false,
			isTrue: false,
			isAnswer: false,
			listAnswer: []
		}
	},
	onLoad(option) {
		// const { exercId, courseId } = params
		this.isJiexi = option.isJiexi=='true' ? true : false
		this.isTrue = option.isTrue == '1' ? true : false
		this.isAnswer = option.isAnswer == '1' ? true : false
		this.surveyId = option.id
		this.$nextTick(async (e) => {
			this.queryExerc(option.id)
		})
	},
	onUnload() {
		clearInterval(this.exercTimer)
	},
	onNavigationBarButtonTap() {
		this.$as.message('左右滑动可切换题目', 'info')
	},
	onBackPress() {
		if (this.canback) return false
		else {
			return this.showBackDialog(), true
		}
	},
	computed: {
		// 判断是否作答完毕
		isAnswered() {
			let result = true
			this.exercList.forEach(p => {
				if (!p.select && !p.input) {
					result = false
				}
			})
			return result
		}
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		queryExerc(suveryId) {
			this.handleExerc(suveryId)
		},
		async handleExerc(suveryId) {
			let riderInfo = uni.getStorageSync('riderInfo')
			const exercJson = mockJson
			// this.exercConfig = exercJson['formConfig']
			// 处理题目
			let tmpList = []
			// expTopic(exercJson['widgetList'], tmpList)
			console.log('tmpList', tmpList)
			this.$api.questionnaire.getLabelBySurveyId(suveryId).then(async (res) => {
				this.labelId = res.data[0].id
				let { data } = await this.$api.questionnaire.qlistByLabelId(res.data[0].id)
				if (this.isAnswer) {
					const param = {
						surveyId: this.surveyId,
						labelId: res.data[0].id,
						userId: riderInfo.question
					}
					let { rows } = await this.$api.questionnaire.listAnswer(param)
					this.listAnswer = rows
				}
				data.forEach((v) => {
					if (v.questionType != '2') {
						let score = v.options.reduce((total, current) => total + (Number(current.optionWeight) || 0), 0);
						let correct = v.options
							.map((item, index) => item.optionWeight !== 0 && item.optionWeight !== null ? index : -1)
							.filter(index => index !== -1).map(index => String.fromCharCode(65 + index));
						let updatedQuestions = v.options.map((item, index) => ({
							value: String.fromCharCode(65 + index),   // 将 questionWeight 改为 value
							label: item.optionText,    // 假设 label 等于 questionWeight 的值
							optionId: item.optionId
						}));
						let obj = {
							questionId: v.questionId,
							correct: v.questionType == '0' ? correct[0] : correct,
							errorRes: v.questionDesc,
							index: 1,
							label: v.questionType == '0' ? "radio" : "multiple",
							name: (v.questionType == '0' ? "radio" : "multiple") + Math.random(),
							optionItems: updatedQuestions,
							score: score,
							select: "",
							topic: v.questionName,
							type: v.questionType == '0' ? "radio" : "multiple",
						}
						// let obj = {
						// 	"type": v.questionType == '0'?"radio":"multiple",
						// 	"icon": v.questionType == '0'?"radio-field":"multiple-field",
						// 	"formItemFlag": true,
						// 	"options": {
						// 		"topic": v.questionName,
						// 		"score": score,
						// 		"index": 1,
						// 		"correct": correct,
						// 		"errorRes": "无",
						// 		"optionItems": updatedQuestions,
						// 		"name": v.questionType == '0'?"radio98024":"multiple67251",
						// 		"label": v.questionType == '0'?"radio":"multiple"
						// 	},
						// 	"id": "radio98024"
						// }
						tmpList.push(obj)
					} else {
						let obj = {
							questionId: v.questionId,
							correct: v.options[0].optionText,
							errorRes: v.questionDesc,
							index: 1,
							label: "input",
							name: "input" + Math.random(),
							optionItems: [],
							score: v.options[0].optionWeight,
							select: "",
							topic: v.questionName,
							type: "input",
						}
						tmpList.push(obj)
					}
				})
				this.exercList = tmpList
				let videoInfo = uni.getStorageSync('videoInfo')
				let RES = await this.$api.questionnaire.surveyInfo(suveryId)
				if (RES.data.submitSet == '4' && this.isAnswer) {
					this.isTrue = true
				}
				if (RES.data.submitSet == '5'&& this.isAnswer) {
					this.isJiexi = true
				}
				this.exercConfig = {
					"labelPosition": "top",
					"size": "",
					"labelAlign": "label-left-align",
					"layoutType": "Pad",
					"exercId": "mockexerc1",
					"exercTitle": res.data[0].label,
					"exercCount": tmpList.length,
					"pass": RES.data.pass,
					"exercScore": RES.data.surveyValue,
					"exercTime": RES.data.duration,
					"createTime": RES.data.createTime,
					"createPerson": "管理员",
					"showRanking": RES.data.showRanking,
					"submissionSet": RES.data.submissionSet,
					"submitSet": RES.data.submitSet,
					"submitShow": RES.data.submitShow,
					"isTrue": this.isTrue,
					"labelWidth": 140
				}

				// 开始倒计时 
				const { exercTime, exercTitle, exercId,
					exercScore, exercCount, pass } = this.exercConfig
				if (exercTitle) {
					uni.setNavigationBarTitle({ title: exercTitle })
				}
				this.minutes = exercTime
				console.log('this.exercList', this.exercList)
				if (this.isAnswer) {

					let result = this.listAnswer.reduce((acc, curr) => {
						// 如果 accumulator 中已经有这个 id，则将 v 添加到该 id 对应的数组中
						if (!acc[curr.questionId]) {
							acc[curr.questionId] = [];  // 如果没有这个 id，先初始化一个空数组
						}
						acc[curr.questionId].push(curr.optionId != 0 ? curr.optionId : 'input-' + curr.extendValue);
						return acc;
					}, {});

					let finalResult = Object.keys(result).map(key => {
						return {
							key: parseInt(key),  // id 作为 key
							value: result[key].join(',')  // 将 v 的值拼接成字符串
						};
					});

					console.log(finalResult)

					// 字母映射
					const indexToLetter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];

					// 查找b中每个option的下标，返回结果

					// 查找 b 中的 id 和 a 中的 key 是否匹配
					let result2 = finalResult.map(item => {
						let value = item.value;  // 获取 a 中每个对象的 value
						let matchedIndexes = [];

						// 在 b 中查找对应的 id
						this.exercList.forEach(bItem => {
							if (bItem.questionId === item.key) {  // 对比 a 中的 key 和 b 中的 id
								// 如果匹配，遍历 bItem 中的 options 查找与 a 中 value 匹配的项
								bItem.optionItems.forEach((opt, index) => {
									if (String(opt.optionId) === value) {
										matchedIndexes.push(index);  // 存储匹配的下标
									}
								});
							}
						});

						// 将下标转换为字母（A~L）
						let letterValue = matchedIndexes.map(index => indexToLetter[index]).join(',');

						// 返回一个包含 key 和字母下标的对象
						return {
							key: item.key,
							value: letterValue
						};
					});

					console.log(result2)

					this.exercList.forEach(v => {
						finalResult.forEach(k => {
							if (v.questionId == k.key) {
								if (k.value.includes('input-')) {
									v.input = k.value.split('input-')[1];
									v.text = k.value.split('input-')[1];
								}
								v.selectId = k.value
							}
						})
						result2.forEach(k => {
							if (v.questionId == k.key) {
								v.select = k.value
							}
						})
					})

					// this.exercList = arr
					this.showPage = true
					return
				}
				if (this.isJiexi) {
					this.exercList = uni.getStorageSync('exercList')
					this.showPage = true
					return
				}
				// 弹出确认框
				uni.showModal({
					title: '温馨提示',
					content: `试题加载成功，考试时间为`
						+ `${exercTime}分钟，确认后将开始倒计时。`,
					confirmColor: '#0B56B1',
					success: (e) => {
						if (e.confirm) {
							this.showPage = true
							Object.assign(this.submitData, {
								start_time: new Date().getTime(),
								total_score: exercScore,
								pass: pass,
								ranking: [],
								submitSet: this.exercConfig.submitSet,
								submitShow: this.exercConfig.submitShow,
								total_count: exercCount,
								exerc_name: exercTitle,
								exerc_id: exercId,
								total_time: exercTime
							})
							startCountdown.apply(this);
						}
						if (e.cancel) {
							uni.navigateBack()
						}
					}
				})
			})
		},
		// 题目选择
		itemSelect(data) {
			if (data.index + 1 === this.exercConfig.exercCount)
				return
			this.swiperIndex = data.index + 1
		},
		showBackDialog() {
			// this.$as.confirm('温馨提示', '当前尚未提交习题练习，'+
			// 	'退出将导致答题数据丢失，是否确认要退出？',
			// () => {

			// })
			this.canback = true
			uni.navigateBack()
		},
		resultFunc(data) {
			uni.redirectTo({
				url: `/pages/webIndex-questions/main/index?id=${this.surveyId}&isJiexi=true&isTrue=${data}`
			})
		},
		async formSubmit() {

			if (!this.isAnswered && this.exercConfig.submissionSet == '0') {
				uni.showToast({ title: '请尚未完成作答，请将所有题目作答完成后提交！', icon: 'none', duration: 1500 })
				return
			} 

			console.log(this.exercList)
			uni.setStorageSync('exercList', this.exercList)
			let riderInfo = uni.getStorageSync('riderInfo')
			this.exercList.forEach(qitem => {
				if (qitem.selectId && JSON.stringify(qitem.selectId).includes(',')) {
					let arr = qitem.selectId.split(',')
					arr.forEach(k => {
						const a = {};
						a.surveyId = this.surveyId;
						a.userId = riderInfo.question;
						a.userName = riderInfo.ridersName;
						a.labelId = this.labelId;
						a.questionId = qitem.questionId;
						a.optionId = k;
						a.extendValue = qitem.input;
						this.answer.push(a);
					})
				} else if (qitem.selectId || qitem.input) {
					const a = {};
					a.surveyId = this.surveyId;
					a.userId = riderInfo.question;
					a.userName = riderInfo.ridersName;
					a.labelId = this.labelId;
					a.questionId = qitem.questionId;
					a.optionId = qitem.input ? 0 : qitem.selectId;
					a.extendValue = qitem.input;
					this.answer.push(a);
				}
			})
			if (isEmpty(this.answer)) {
				let { code } = await this.$api.questionnaire.addKaoLog({ surveyId: this.surveyId, userId: riderInfo.question })
				if (this.exercConfig.showRanking == 1) {
					this.$api.questionnaire.listPaihang({ examId: this.surveyId }).then(res => {
						this.submitData.ranking = res.rows
					})
				}
				let sbExerc = () => {
					let subData = handleSubmit.apply(this)
					this.canback = true
					this.showPage = false
					this.showResult = true
				}
				
				sbExerc()
				return
			}


			this.$api.questionnaire.collectAnswers(this.answer).then(res => {
				console.log(res)
				//判断是否添加成功，添加成功flag+1
				if (res.code == 200) {
					if (this.exercConfig.showRanking == 1) {
						this.$api.questionnaire.listPaihang({ examId: this.surveyId }).then(res => {
							this.submitData.ranking = res.rows
							let sbExerc = () => {
								let subData = handleSubmit.apply(this)
								this.canback = true
								this.showPage = false
								this.showResult = true
							}
							if (!this.isAnswered) {
								sbExerc()
								// this.$as.confirm('温馨提示', '当前练习题还没有做完，是否继续提交？',
								// () => sbExerc())
							} else {
								sbExerc()
							}
						})
					} else {
						let sbExerc = () => {
							let subData = handleSubmit.apply(this)
							this.canback = true
							this.showPage = false
							this.showResult = true
						}
						if (!this.isAnswered) {
							sbExerc()
							// this.$as.confirm('温馨提示', '当前练习题还没有做完，是否继续提交？',
							// () => sbExerc())
						} else {
							sbExerc()
						}
					}

				}
			})
		},
		// 提交题目
		submitExerc() {
			this.show2 = true
		},
		swiperChange(event) {
			const { current } = event.detail
			this.swiperIndex = current
		},
		// 答题卡选择
		sheetSelect(index) {
			this.swiperIndex = index
			this.showExerc = true
		},
	}
}

</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>